package com.ant.business.system.service.impl;

import com.ant.business.system.entity.Module;
import com.ant.business.system.entity.Role;
import com.ant.business.system.entity.RoleModule;
import com.ant.business.system.mapper.RoleDao;
import com.ant.business.system.mapper.RoleModuleDao;
import com.ant.business.system.service.RoleService;
import com.ant.business.system.vo.UserVo;
import com.ant.common.constant.SystemConstant;
import com.ant.common.exceptions.BusinessException;
import com.ant.common.utils.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 角色管理Service实现类
 * @author
 * @description
 * @create 2021-03-22 14:25:56
 */
@Service("roleService")
@Transactional(rollbackFor = Throwable.class)
public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService {

    private final RoleDao roleDao;

    private final RoleModuleDao roleModuleDao;

    public RoleServiceImpl(RoleDao roleDao, RoleModuleDao roleModuleDao) {
        this.roleDao = roleDao;
        this.roleModuleDao = roleModuleDao;
    }

    /**
     * 分页查询列表
     * @param page
     * @param limit
     * @param param
     * @return
     */
    @Override
    public PageInfo<Role> getList(int page, int limit, FastMap param) {
        UserVo user = UserThreadLocal.getUser();
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("delete_flag", SystemConstant.DELETE_STATUS.UN_DELETE.getCode()).eq("unit_id", user.getUnitId());

        if (StringUtil.isNotEmpty(param.getString("roleName"))){
            wrapper.like("role_name", param.getString("roleName"));
        }

        PageHelper.startPage(page, limit);
        List<Role> list = roleDao.selectList(wrapper);
        return new PageInfo<Role>(list);
    }

    /**
     * 检查用户信息
     * @param role
     * @return
     */
    private boolean checkInfoExists(Role role){
        UserVo user = UserThreadLocal.getUser();
        List<Role> roleList = this.list(new QueryWrapper<Role>().eq("role_name", role.getRoleName()).eq("unit_id", user.getUnitId()));
        return roleList.size()!=0;
    }

    /**
     * 新增信息
     * @param role
     */
    @Override
    @SneakyThrows
    public void saveOne(Role role) {
        UserVo user = UserThreadLocal.getUser();
        if (checkInfoExists(role)){
            throw new BusinessException("角色名称不能重复");
        }

        role.setUnitId(user.getUnitId());
        LocalBeanUtil.setLoginUserInfo(role);
        role.setDeleteFlag(SystemConstant.DELETE_STATUS.UN_DELETE.getCode());
        int count = roleDao.insert(role);
        if (count!=1){
            throw new BusinessException("角色保存失败");
        }
    }

    /**
     * 更新信息
     * @param role
     */
    @Override
    @SneakyThrows
    public void update(Role role) {
        LocalBeanUtil.updateLoginUserInfo(role);
        int count = roleDao.updateById(role);
        if (count!=1){
            throw new BusinessException("角色更新失败");
        }
    }

    /**
     * 删除信息
     * @param primaryKey
     */
    @Override
    @SneakyThrows
    public void delete(String primaryKey) {
        Role role = roleDao.selectById(primaryKey);

        Role newRole = new Role();
        newRole.setRoleId(Integer.valueOf(primaryKey));
        LocalBeanUtil.updateLoginUserInfo(newRole);
        newRole.setDeleteFlag(SystemConstant.DELETE_STATUS.DELETED.getCode());
        newRole.setRoleName(role.getRoleName() + "_" + IdWorker.get32UUID());

        int count = roleDao.updateById(newRole);
        if (count != 1) {
            throw new BusinessException("角色删除失败");
        }
    }

    /**
     * 绑定角色对应的模块
     * @param param
     */
    @Override
    @SneakyThrows
    public void updateRoleModule(FastMap param) {
        UserVo user = UserThreadLocal.getUser();
        int roleId = param.getInt("roleId");
        if (roleId == 0) {
            throw new BusinessException("请选择角色");
        }
        roleModuleDao.delete(new QueryWrapper<RoleModule>().eq("unit_id", user.getUnitId()).eq("role_id", roleId));
        Object moduleIdsObj = param.get("moduleIds");
        List<Integer> moduleIds = new ArrayList<>();
        if (Objects.nonNull(moduleIdsObj) && moduleIdsObj instanceof List) {
            moduleIds = (List<Integer>) moduleIdsObj;
        }

        if (moduleIds.size() == 0) {
            throw new BusinessException("请选择模块");
        }

        moduleIds = moduleIds.stream().filter(x -> x > 0).collect(Collectors.toList());
        for (Integer moduleId : moduleIds) {
            RoleModule roleModule = new RoleModule();
            roleModule.setRoleId(roleId);
            roleModule.setModuleId(moduleId);
            roleModule.setUnitId(user.getUnitId());
            int insert = roleModuleDao.insert(roleModule);
            if (insert!=1) {
                throw new BusinessException("写入角色模块表失败");
            }
        }
    }

    @Override
    @SneakyThrows
    public List<Module> getRoleModuleList(FastMap param) {
        int roleId = param.getInt("roleId");
        if (roleId == 0) {
            throw new BusinessException("请选择角色");
        }
        return roleModuleDao.getRoleModuleList(roleId);
    }
}
